<script setup>
import { inject, ref } from "vue";
import stepsview from "../components/steps/steps.vue";
import { useCounterStore } from "@/stores/upgrade";
import { handleGoBack } from "@/utils/router";
import {
  upgradecreate,
  upgradeagreeInfo,
  upgradedetails,
} from "@/services/upfrade";
import { uploadfile } from "@/services/upload";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { base_URL } from "@/utils/http";

import { baseagree } from "@/services/user";

const level_id = ref("");
const id = ref("");
const product_id = ref("");
const type = ref("");
const pay_status = ref("");
const agree = ref("");
const content = ref({});
const contentobj = ref({});

const isCountDown = ref(false);
onLoad((e) => {
  level_id.value = e.level_id ? e.level_id : "";
  id.value = e.id ? e.id : "";
  product_id.value = e.product_id ? e.product_id : "";
  type.value = e.type ? e.type : "";
  pay_status.value = e.pay_status ? e.pay_status : "";
  agree.value = e.level_id
    ? "distribution_agency_agree"
    : "service_center_agree";

  baseagreefun();
});

onShow(() => {
  signature.value = "";
});
// const form = useCounterStore ();

const dateobj = useCounterStore();

const current = ref(1);
const signature = ref("");
const file = ref(null);
if (dateobj.formdate.signature) {
  signature.value = dateobj.formdate.signature;
}

async function baseagreefun() {
  let res = await baseagree({ code: agree.value });

  let ress = await upgradedetails({ id: id.value, type: type.value });
  content.value = res.data ? res.data : "";

  contentobj.value = ress.data.agree_text;
}

async function signatureEvent(base64) {
  // #ifdef H5 || APP-PLUS
  signature.value = base64;
  // #endif

  // var imageUrl = createImageUrlFromBase64(base64);
  // #ifdef MP-WEIXIN

  let res = await base64ToTempFilePath(base64);

  signature.value = res;
  // base64ToTempFilePath(
  //   base64,
  //   function (tempFilePath) {
  //     console.log("转换成功，临时地址为:", tempFilePath);
  //     signature.value = tempFilePath; // 会在canvas中调用
  //   },
  //   function () {
  //     console.log("转换失败");
  //   }
  // );

  // #endif
}
async function base64ToTempFilePath(base64Data) {
  const fs = uni.getFileSystemManager();
  const fileName = "LotteryActivity_" + Date.now() + ".png"; // 自定义文件名，可根据需要修改
  const filePath = uni.env.USER_DATA_PATH + "/" + fileName;
  const base64 = base64Data.split(",")[1]; //移除固定头部
  const buffer = uni.base64ToArrayBuffer(base64);
  let promise = await new Promise((resolve, reject) => {
    fs.writeFile({
      filePath,
      data: buffer,
      encoding: "binary",
      success(res) {
        resolve(filePath); // fulfilled
      },
      fail(err) {
        reject(err); // rejected
      },
    });
  });
  return promise;
}
function clearshart() {
  signature.value = "";
  file.value = "";
}

const time = ref(10);
const onChange = (e) => {
  time.value = e.seconds;
};
const lastfun = () => {
  uni.navigateBack();
};

const nextfun = async () => {
  if (time.value > 0) {
    return;
  }
  if (!signature.value) {
    uni.$u.toast("请上传签名");
    return;
  }

  uni.uploadFile({
    url: base_URL + "/api/upload/file",
    filePath: signature.value,
    name: "file",
    formData: {
      user: "test",
    },
    header: {
      Authorization: uni.getStorageSync("Authorization"),
    },
    success: async (uploadFileRes) => {
      let data = JSON.parse(uploadFileRes.data);
      if (data.code == 200) {
        try {
          let ress = await upgradeagreeInfo({
            id: id.value,
            signature: data.data.url,
            type: type.value,
          });
          if (ress.code == 200) {
            dateobj.formdate.signature = data.data.url;

            // level_id.value = e.level_id ? e.level_id : "";
            // id.value = e.id ? e.id : "";
            // product_id.value = e.product_id ? e.product_id : "";
            if (pay_status.value) {
              dateobj.setformdate({});
              uni.reLaunch({
                url: "/pages/upgrade/upgradestate?type=1",
              });
            } else {
              uni.navigateTo({
                url:
                  "/pages/upgrade/upgradepay?level_id=" +
                  (level_id.value ? level_id.value : "") +
                  "&id=" +
                  id.value +
                  "&product_id=" +
                  (product_id.value ? product_id.value : "") +
                  "&type=" +
                  type.value,
              });
            }
          }
        } catch (e) {
          uni.$u.toast(e.info);
          if (pay_status.value) {
            dateobj.setformdate({});
            uni.reLaunch({
              url: "/pages/upgrade/upgradestate?type=2",
            });
          }
        }
      }
    },
    fail: function (e) {
      uni.hideLoading();
    },
  });

  return;
};

const finushfun = () => {
  isCountDown.value = true;
};
</script>

<template>
  <view class="upgrade">
    <stepsview :current="current"></stepsview>

    <view class="agreement-content">
      <view class="agreement-title"></view>
      <view class="agreement-text"
        ><up-parse
          if="content.content"
          :content="content.content ? content.content : ''"
        ></up-parse>
      </view>
      <image class="signature-img" :src="signature" mode="scaleToFill" />

      <view class="signature-k">
        <xz-signature ref="signqm" @clear="clearshart" @save="signatureEvent" />
      </view>
    </view>
  </view>

  <view class="foodr-bt">
    <view class="bt-next" @click="lastfun">上一步</view>
    <view
      class="bt-sbuit"
      @click="nextfun"
      :class="!isCountDown ? 'bt-sbuit-none' : ''"
      ><u-count-down
        :time="15 * 1000"
        format="ss"
        @finish="finushfun"
        @change="onChange"
        ><text v-if="!isCountDown">{{ time + 1 }}秒后</text>
        同意协议</u-count-down
      >
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "./agreement.scss";
</style>
